import moment from 'moment';
import React from 'react';
import { connect } from 'dva';
import { stringify } from 'qs';
import { ContentPackage, DATA_ENTRY, AdvancedSearch, InfoTipsC, PrimaryC, PrimaryGhostC, NoQueryC, ModalC } from '../../../comps';
import { exportFile } from '../../../utils/commonFunc';
import ListTable from './listTable';
import RedirectTable from './modalLayer';
import styles from './index.less';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { message } from 'antd';
class MultiFundDivision extends React.Component {
  constructor() {
    super();
    this.state = {
      firstEnter: true,
      searchParams: {
        temps: new Date().getTime(),
      },
      disabled: true,
      visible: false,
      dValue: null, //差值
      layerColumns: [], //弹窗中的columns
      selectNeedHandleTable: null, //存储选中的select的地方
      WrapperTableList: [], //外部的表格
      layerTitle: '确认划款',
      temp: new Date().getTime(),
    };
  }
  //查询按钮
  onQuery = (e) => {
    if (!e || !e.productGroupId) {
      message.warning('请选择产品组进行查询！');
      return;
    }
    this.setState({
      firstEnter: false,
      searchParams: {
        productGroupId: e?.productGroupId,
        temps: new Date().getTime(),
      },
      disabled: true,
      temp: new Date().getTime(),
    });
  };
  //划款指令
  directDivide = () => {
    //换算出差值
    let compareValue;
    compareValue = this.child.state?.tableList && this.child.state.tableList[0].dValue;
    let newArrSelect = this.circleHandleDataChoose(this.child.getTableSelect(), this.child.state?.tableList && this.child.state?.tableList[0].nestedConfig.dataSource);
    this.setState({
      selectNeedHandleTable: newArrSelect,
      dValue: compareValue.toFixed(2),
      WrapperTableList: this.child.state.tableList,
      visible: true,
      layerColumns: this.child.state.childColumns,
      layerTitle: '确认划款',
      temp: new Date().getTime(),
    });
  };
  //需要替换勾选的中的值
  circleHandleDataChoose = (data, allData) => {
    if (allData && allData.length) {
      for (var i = 0; i < allData.length; i++) {
        if (data.find((item) => item.key == allData[i].key)) {
          //如果此时可以找到
          data[data.findIndex((item) => item.key == allData[i].key)].cashRate = allData[i].cashRate;
        }
        if (allData[i].children && allData[i].children.length) {
          this.circleHandleDataChoose(data, allData[i].children);
        }
      }
    }
    return data;
  };
  //导出
  export = () => {
    //换算出差值
    let compareValue;
    compareValue = this.child.state?.tableList && this.child.state.tableList[0].dValue;
    let newArrSelect = this.circleHandleDataChoose(this.child.getTableSelect(), this.child.state?.tableList && this.child.state?.tableList[0].nestedConfig.dataSource);
    this.setState({
      selectNeedHandleTable: newArrSelect,
      dValue: compareValue.toFixed(2),
      WrapperTableList: this.child.state.tableList,
      visible: true,
      layerColumns: this.child.state.childColumns,
      layerTitle: '确认导出',
      temp: new Date().getTime(),
    });
  };
  //重置按钮
  onClear = () => {};
  //左侧的内容
  leftContent = () => {
    return <div>日期：{moment().format('YYYY-MM-DD')}</div>;
  };
  //处理弹窗中的数组数据变成扁平的处理
  circlelist = (newArr, list) => {
    for (let i = 0; i < list.length; i++) {
      let newA = JSON.parse(JSON.stringify(list[i]));
      if (newA?.children?.length) {
        delete newA.children;
      }
      newArr.push(newA);
      if (list[i].children && list[i].children.length) {
        this.circlelist(newArr, list[i].children);
      }
    }
  };
  //递归改变页面的数据
  circleChangeOrigin = (originList, newArr) => {
    for (let k = 0; k < originList.length; k++) {
      if (newArr.findIndex((item) => item.key == originList[k].key) >= 0) {
        let index_ = newArr.findIndex((item) => item.key == originList[k].key);
        originList[k].cashRate = newArr[index_].cashRate;
      }
      //如果改的是children中的值
      if (originList[k].children && originList[k].children.length) {
        this.circleChangeOrigin(originList[k].children, newArr);
      }
    }
    return originList;
  };
  //点击确定按钮
  confirmAddProduct = () => {
    const { layerTitle, searchParams } = this.state;
    let datas = this.props.form.getFieldsValue().plans;
    //处理勾选的改变的值
    let newArr = [];
    //这个是获取弹窗中datas的数据进行平铺
    this.circlelist(newArr, datas);
    //继续判断是否有未保存的数据
    if (newArr.find((item) => item.edit)) {
      message.warning('表单需要保存后才可进行提交！');
      return;
    }
    //保存成功后页面中表格的数据要发生改变

    let newDatas = JSON.parse(JSON.stringify(this.child.state.tableList));
    let counts = 0;
    newArr.forEach((item) => {
      counts += Number(item.cashRate);
    });

    newDatas[0].totalrate = counts.toFixed(2);
    newDatas[0].dValue = counts.toFixed(2) - newDatas[0].actualRate;
    //需要将弹窗中的值改变之后 需要更新table表格中的值
    let originList = newDatas[0].nestedConfig.dataSource;
    this.circleChangeOrigin(originList, newArr);

    //对newArr进行克隆
    let newArr_ = JSON.parse(JSON.stringify(newArr));
    newArr_.map((item) => {
      delete item.key;
      delete item.edit;
      delete item.level;
    });

    if (layerTitle == '确认划款') {
      this.props.dispatch({
        type: 'multiFundDivisionM/comfirmDivide',
        payload: {
          datas: newArr_,
          compareRate: newDatas[0].dValue,
          adtualRate: newDatas[0].actualRate,
          productGroupId: searchParams.productGroupId,
        },
        callback: (res) => {
          if (res) {
            message.success('确认划款成功！');
            //弹窗关闭
            this.setState(
              {
                visible: false,
              },
              () => {
                this.child.setState({
                  tableList: newDatas,
                });
              },
            );
          }
        },
      });
    } else {
      //导出
      let params = {
        datas: JSON.stringify(newArr_),
      };
      exportFile('api/v1/rate/exportData', params);
      //弹窗关闭
      this.setState(
        {
          visible: false,
        },
        () => {
          this.child.setState({
            tableList: newDatas,
          });
        },
      );
    }
  };
  //递归取消事件
  circleTableCancel = (list) => {
    for (let i = 0; i < list.length; i++) {
      if (list[i]?.edit) {
        list[i].edit = false;
        if (list[i].children && list[i].children.length) {
          this.circleTableCancel(list[i].children);
        }
      }
    }
    return list;
  };
  //点击取消按钮
  handleCancelAdd = () => {
    //点击取消的时候 需要将之前的edit状态清空
    let datas = this.props.form.getFieldsValue().plans;
    let arrs = this.circleTableCancel(datas);
    this.setState(
      {
        visible: false,
      },
      () => {
        this.props.form.setFieldsValue({
          plans: arrs,
        });
      },
    );
  };
  //处理disabled的状态
  render() {
    const _parentThis = this;
    const { firstEnter, searchParams, disabled, selectNeedHandleTable, dValue, layerColumns, WrapperTableList, layerTitle, temp } = this.state;
    const { getFieldDecorator } = this.props.form;
    const dataSource = [
      {
        title: '产品组',
        dataIndex: 'productGroupId',
        multiple: false,
        type: DATA_ENTRY.PRODUCTGROUP,
        tradeModel: ['BOOKKEEPING_MODE', 'COMMAND_MODE'], //不包含估值解析和估值对接的产品
      },
    ];
    //划款指令的模态框
    const modalProps = {
      visible: this.state.visible,
      // confirmLoading:loading.effects['initialSplitM/uploadFile'] === true,
      onOk: () => {
        this.confirmAddProduct();
      },
      onCancel: () => {
        this.handleCancelAdd();
      },
      title: layerTitle,
      width: 720,
    };
    return (
      <ContentPackage
        title='多基金划款'
        contentHtml={
          <div>
            <AdvancedSearch dataSource={dataSource} onQuery={this.onQuery} onClear={this.onClear} />
            <div className={styles.barInfo}>
              <div>
                <PrimaryC title='划款指令' onClick={this.directDivide} disabled={disabled} />
              </div>
              <div className={styles.infos}>
                <InfoTipsC Left={this.leftContent()} width='100%' style={{ paddingLeft: '20px' }} />
              </div>
              <div>
                <PrimaryGhostC title='导出' onClick={this.export} disabled={disabled} />
              </div>
            </div>
            <div>
              <ModalC {...modalProps}>
                {/* 这边需要传入选中的数据 以及 差值  以及真实金额的值 */}
                {getFieldDecorator('plans', {
                  // 使用getFieldDecorator用于进行双向绑定，存取我们需要的value
                  initialValue: selectNeedHandleTable, // 设定我们的初始值，模块化的开发，
                  // 让我们更有利的维护我们的开发成本，只需要维护当前主界面
                })(
                  <RedirectTable
                    temp={temp}
                    selectNeedHandleTable={selectNeedHandleTable}
                    form={this.props.form}
                    dValue={dValue}
                    layerColumns={layerColumns}
                    actualRate={WrapperTableList && WrapperTableList.length && WrapperTableList[0].actualRate}
                  ></RedirectTable>,
                )}
              </ModalC>
              {firstEnter ? <NoQueryC /> : <ListTable searchParams={searchParams} _parentThis={_parentThis} onRef={(ref) => (this.child = ref)} />}
            </div>
          </div>
        }
      />
    );
  }
}
export default Form.create()(connect(({ multiFundDivisionM }) => ({ multiFundDivisionM }))(MultiFundDivision));
